package com.pkk.penguin.components.stater.exception.handler;

import com.pkk.components.rpc.response.CommonResponse;
import com.pkk.components.rpc.response.util.ResponseUtil;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * @author luffy
 * @description: 全局异常处理controller
 * @date 2019-11-14 14:32
 */
@Slf4j
@RestController
public class ExceptionController implements ErrorController {

  @Autowired
  private ErrorAttributes errorAttributes;

  /**
   * 默认错误
   */
  public final static String ERROR_PATH = "/error";

  @Override
  public String getErrorPath() {
    return ERROR_PATH;
  }

  @RequestMapping(value = ERROR_PATH, produces = {MediaType.APPLICATION_JSON_VALUE})
  public CommonResponse error(HttpServletRequest request) {
    Map<String, Object> body = getErrorAttributes(request);
    HttpStatus status = getStatus(request);
    body.put("status", status.value());
    return ResponseUtil.error(body.toString());
  }

  /**
   * 错误信息详情map
   *
   * @param request
   * @return ErrorAttributes
   */
  private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
    ServletWebRequest servletWebRequest = new ServletWebRequest(request);
    Map<String, Object> map = errorAttributes.getErrorAttributes(servletWebRequest, isTrace(request));
    if (request.getAttribute("status") instanceof Integer) {
      map.put("status", request.getAttribute("status"));
    }
    map.put("url", request.getRequestURL().toString());
    map.putIfAbsent("path", request.getAttribute("raw_url"));
    log.error("error occurred, status={}, path={}, msg={}, error={}, exception={}", map.get("status"),
        map.get("path"), map.get("message"), map.get("error"), map.get("exception"));
    return map;
  }

  /**
   * 获取状态码
   *
   * @param request HttpServletRequest
   * @return HttpStatus
   */
  private HttpStatus getStatus(HttpServletRequest request) {
    Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
    if (statusCode == null) {
      return HttpStatus.INTERNAL_SERVER_ERROR;
    }
    return HttpStatus.valueOf(statusCode);
  }

  /**
   * 是否打印错误信息
   *
   * @param request HttpServletRequest
   * @return if trace error
   */
  private boolean isTrace(HttpServletRequest request) {
    String parameter = request.getParameter("trace");
    if (parameter == null) {
      return false;
    }
    return !"false".equals(parameter.toLowerCase());
  }
}
